using MovieApi.DB;
using MovieApi.Dto;
using MovieApi.Common;
using Microsoft.AspNetCore.Mvc;
using MovieApi.Model;
using MovieApi.Interfaces;

namespace MovieApi.Controllers;

[ApiController]
[Route("api/[controller]")]
public class MovieController : ControllerBase
{
    private readonly IRepository<Movie> _movieRep;
    public MovieController(IRepository<Movie> movieRep)
    {
        _movieRep = movieRep;
    }

    [HttpGet]
    public async Task<IActionResult> GetAll()
    {
        var list = await _movieRep.GetAllAsync();
        if (list.Count == 0)
        {
            return Ok(ApiResponse<string>.Fail(1004, "暂无电影"));
        }
        return Ok(ApiResponse<List<Movie>>.Success(list));
    }

    [HttpPost]
    public async Task<IActionResult> Add(MovieDto movieDto)
    {
        var movie = new Movie { MovieName = movieDto.MovieName, Classify = movieDto.Classify };
        await _movieRep.AddAsync(movie);
        return Ok(ApiResponse<Movie>.Success(movie));
    }

    [HttpPut("{id}")]
    public async Task<IActionResult> Edit(int id, MovieDto movieDto)
    {
        var movie = await _movieRep.GetByIdAsync(id);
        if (movie == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无该电影,修改失败"));
        }
        movie.MovieName = movieDto.MovieName;
        movie.Classify = movieDto.Classify;
        await _movieRep.UpdateAsync(movie);
        return Ok(ApiResponse<MovieDto>.Success(movieDto,"修改成功"));
    }

    [HttpDelete("{id}")]
     public async Task<IActionResult> Del(int id)
    {
        var movie = await _movieRep.GetByIdAsync(id);
        if (movie == null)
        {
            return Ok(ApiResponse<string>.Fail(1004, "查无该电影,删除失败"));
        }
        await _movieRep.DeleteAsync(movie);
        return Ok(ApiResponse<Movie>.Success(movie,"删除成功"));
    }

}